package com.gs.disk.modules.headImgAndWallper.service.admin;


import cn.hutool.core.convert.Convert;
import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.gs.entity.GeneralPage;

import com.gs.common.util.*;

import com.gs.disk.controller.common.OssController;
import com.gs.disk.modules.headImgAndWallper.dao.admin.AdminResourceDao;
import com.gs.disk.modules.headImgAndWallper.dto.ResourceDto;
import com.gs.disk.modules.headImgAndWallper.entity.ResourceEntity;
import com.gs.disk.service.common.OssService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.*;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;

@Service
@Slf4j
public class AdminResourceService extends ServiceImpl<AdminResourceDao, ResourceEntity> {

   @Resource
   private AdminResourceDao dao;

    @Resource
    private OssService ossService;

    @Resource
    private OssController ossController;

    @Resource
    private FileUtils fileUtils;

    @Resource
    private MinIOUtil minIOUtil;

    public void delete(Long id) {
        dao.deleteById(id);
    }

    public void upsert(ResourceEntity entity) {

        dao.insertOrUpdate(entity);
    }

    /**
     * 资源列表
     * @param params
     * @return
     */
    public GeneralPage<ResourceDto> list(Map<String, Object> params) {
        Object categoryId = params.get("categoryId");
        Object page = params.get("page");
        Object limit = params.get("limit");
        QueryWrapper<ResourceEntity> wrapper = new QueryWrapper<>();

        if(ObjectUtil.isNotEmpty(categoryId)) {
            wrapper.eq("category_id", categoryId);
        }

        wrapper.orderByDesc("update_time");

        GeneralPage generalPage = SQLUtils.toPageSql(dao, wrapper, page, limit);
        List list = generalPage.getList();

        List<ResourceDto> result = new LinkedList<>();
        list.forEach(l -> {
            ResourceDto resourceDto = ConvertUtils.sourceToTarget(l, ResourceDto.class);

            Long ossFileId = resourceDto.getOssFileId();
            if(ObjectUtil.isNotEmpty(ossFileId)) {
                String ossFileURL = ossService.getDownloadURL(ossFileId);
                resourceDto.setFileUrl(ossFileURL);
                String oldFileName = resourceDto.getOldFileName();
            }

            Long thumbnailFileId = resourceDto.getThumbnailFileId();

            if(ObjectUtil.isNotEmpty(thumbnailFileId)) {
                String downloadURL = ossService.getDownloadURL(thumbnailFileId);
                resourceDto.setThumbnailFileUrl(downloadURL);
            }
            result.add(resourceDto);
        });
        generalPage.setList(result);
        return generalPage;
    }

    public void batchSave(List<ResourceEntity> resourceList) {
        for (ResourceEntity resourceEntity : resourceList) {
            dao.insertOrUpdate(resourceEntity);
        }
    }

    /**
     * 生成缩略图
     * @param categoryId
     * @param scale 缩放比例
     */
    public void generateThumbnailFile(Long categoryId, String scale) throws Exception {
        List<ResourceEntity> list = dao.list(categoryId);
        String tempResourcePath = fileUtils.getTempResourcePath();

        for (int i = 0; i < list.size(); i++) {
            ResourceEntity l = list.get(i);

            if(l.getOldFileName().endsWith(".webp")) continue;
            if(l.getOldFileName().endsWith(".jfif")) continue;

            Long ossFileId = l.getOssFileId();
            InputStream inputStream = ossService.getObject(ossFileId);
            File file = new File(tempResourcePath + l.getOldFileName());
            String absolutePath = file.getAbsolutePath();
            String newFileAbsolutePath = absolutePath.replace(".", ".copy.");


            BufferedOutputStream out = null;

            File outPutFile = new File(absolutePath);
            if(!outPutFile.exists()) {
                outPutFile.createNewFile();
            }
            out=new BufferedOutputStream(new FileOutputStream(outPutFile));
            int len=-1;
            byte[] b=new byte[1024];
            while((len=inputStream.read(b))!=-1){
                out.write(b,0,len);
            }
            inputStream.close();
            out.close();

            ImageUtils.imgScale(absolutePath, newFileAbsolutePath, Convert.toDouble(scale));
            log.info("copyImage" + i);

            MultipartFile multipartFile = fileUtils.getMultipartFile(new File(newFileAbsolutePath));

            String path = "/wallper/" + DateTimeUtil.currentTimeUTf8();

            // 上传文件的path必须以“/”结尾
            if(path != null && !path.endsWith("/")) {
                path += "/";
            }

            Object fileId = ossController.upload(multipartFile, minIOUtil.getBucketName() , path).getData();

            l.setThumbnailFileId(Convert.toLong(fileId));
        }

        updateBatchById(list);
    }

    public Integer getMaxSort() {

        return dao.getMaxSort();
    }
}
